package com.chz.SupermarketMS.controllers;

import com.chz.SupermarketMS.dao.HeadRepository;
import com.chz.SupermarketMS.dao.SaleRepository;
import com.chz.SupermarketMS.dto.SaleHeads;
import com.chz.SupermarketMS.entities.Commodity;
import com.chz.SupermarketMS.entities.Head;
import com.chz.SupermarketMS.entities.Sale;
import com.chz.SupermarketMS.service.SaleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.validation.Valid;
import java.util.List;

@Controller
@RequestMapping("sales")
public class SaleController {

    @Autowired
    SaleService saleService;

    @Autowired
    HeadRepository headRepository;

    @Autowired
    SaleRepository saleRepository;

    @GetMapping
    public String displaySales(Model model){

        List<Sale> sales = saleService.getAll();
        model.addAttribute("sales",sales);

        List<SaleHeads> saleHeads=saleRepository.saleHeads();
        model.addAttribute("saleHeads",saleHeads);

        return "sales/list-sales";
    }

    @GetMapping("/new")
    public String displaySaleForm(Model model){

        Sale aSale = new Sale();
        model.addAttribute("sale",aSale);
//
//        List<Head> heads=headRepository.findAll();
//        model.addAttribute("allHeads",heads);

        return "sales/new-sale";
    }

    @PostMapping("/save")
    public String createSale(Model model,  @Valid Sale sale,Errors errors){

        if (errors.hasErrors()) return "sales/new-sale";
        saleService.save(sale);
//        Iterable<Head> chosenHeads = headRepository.findAllById(heads);
//        for (Head head : chosenHeads){
//            head.setSales(sale);
//            headRepository.save(head);
//        }
        return "redirect:/sales";
    }
    @GetMapping("/update")
    public String displaySaleUpdateForm(@RequestParam("id") long theId, Model model) {
        Sale theSale = saleService.findBySaleId(theId);
        model.addAttribute("sale", theSale);
        return "sales/new-sale";
    }
    @GetMapping("/delete")
    public String deleteSale(@RequestParam("id")long theId, Model model) {
        Sale theSale = saleService.findBySaleId(theId);
        saleService.delete(theSale);
         return "redirect:/sales";
    }
}
